package com.misalen.retrofit.converter.response;

import java.io.IOException;

import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.ResponseBody;
import retrofit2.Converter;

public final class JsonResponseBodyConverter implements Converter<ResponseBody, JSONObject> {

	public JsonResponseBodyConverter() {

	}

	@Override
	public JSONObject convert(ResponseBody value) throws IOException {
		try {
			JSONObject object = new JSONObject(value.string());
			if (object.getInt("errorCode") == 200) {
				return object.getJSONObject("data");
			} else {
				throw new IOException(object.getString("message"));
			}
		} catch (JSONException e) {
			return null;
		} finally {
			value.close();
		}
	}
}
